<template>
  <div class="container">
    <van-nav-bar
      left-arrow
      @click-left="$router.back()"
      title="编辑资料"
    ></van-nav-bar>
    <van-cell-group>
      <van-cell is-link title="头像" center>
        <div class="user-image">
          <van-image
            slot="default"
            width="1.5rem"
            height="1.5rem"
            fit="cover"
            round
            :src="user.photo"
          />
          <!--  用来选中本地文件
                如何获取这个file文本域中选中的文件？
                把它隐藏起来
          -->
          <input
            class="input-image"
            type="file"
            @change="hPhotoChange"
            ref="refPhoto"
          />
        </div>
      </van-cell>
      <van-cell
        is-link
        title="名称"
        :value="user.name"
        @click="showName = true"
      />
      <van-cell
        is-link
        title="性别"
        :value="user.gender === 1 ? '女' : '男'"
        @click="showGender = true"
      />
      <van-cell
        is-link
        title="生日"
        :value="user.birthday"
        @click="showBirthday = true"
      />
    </van-cell-group>
    <!-- 修改用户名的弹窗 -->
    <van-dialog
      @confirm="editName"
      v-model="showName"
      title="修改用户名"
      show-cancel-button
    >
      <van-cell-group>
        <van-field
          v-model="newName"
          label="用户名"
          placeholder="请输入要修改的用户名"
        />
      </van-cell-group>
    </van-dialog>
    <!-- 修改性别的弹窗 -->
    <van-popup v-model="showGender" round position="bottom">
      <van-picker
        show-toolbar
        title="修改性别"
        :columns="genders"
        @confirm="sexOnConfirm"
        @cancel="sexOnCancel"
        @change="sexOnChange"
      />
    </van-popup>
    <!-- 修改生日 -->
    <van-popup v-model="showBirthday" round position="bottom">
      <van-datetime-picker
        v-model="newDate"
        type="date"
        title="选择年月日"
        :min-date="minDate"
        :max-date="maxDate"
        :formatter="formatter"
        @confirm="editBirth"
        @cancel="birthOnCancel"
      />
    </van-popup>
  </div>
</template>

<script>
import { getUserSelf, updateUserInfo, updatePhoto } from "@/api/user";
export default {
  name: "userProfile",
  data() {
    return {
      // 控制弹层
      showName: false,
      showGender: false,
      showBirthday: false,

      // 当前用户的信息
      user: {},

      // 修改后的新名字
      newName: "",
      // 修改后新生日
      newDate: new Date(),
      minDate: new Date(1965, 0, 10), // dateTime-picker中最小时间
      maxDate: new Date(), // 当前时间
      genders: ["男", "女"],
      newGender: 0
    };
  },
  created() {
    this.getSelfInfo();
  },
  methods: {
    //获取用户个人资料
    async getSelfInfo() {
      try {
        const res = await getUserSelf();
        this.user = res.data.data;
        // this.newName = res.data.data.name;//回显用户名
      } catch {
        this.$toast("获取失败");
      }
    },
    //修改用户名
    async editName() {
      //1.需要一个输入框
      //2.接口调用，发送请求
      // 解决问题
      //1.需要一个有输入框的弹窗
      if (!this.newName) {
        this.$toast("用户名不能为空");
        return;
      }
      try {
        //3.输入新名字  调接口
        //5.调用接口
        await updateUserInfo({
          name: this.newName
        });
        //6.成功了渲染
        this.user.name = this.newName;
        this.newName = "";
      } catch {
        //7.失败了提示
        this.$toast("失败");
      }
    },
    sexOnConfirm(value, index) {
      console.log(value, index);
      this.newGender = index;
      this.editGender();
      this.showGender = false;
    },
    sexOnCancel() {
      this.showGender = false;
    },
    sexOnChange() {
      console.log("change");
      //   this.showGender = true;
    },
    //修改性别
    async editGender() {
      //1.需要一个复选框  男  女  准备一个修改性别的模板  初始化数据
      const newGender = this.newGender;
      if (this.user.gender === newGender) {
        this.$toast("性别未修改，一样的呀");
        return;
      }
      //2.准备接口
      try {
        await updateUserInfo({
          gender: this.newGender
        });
        this.user.gender = newGender;
      } catch {
        this.$toast("失败");
      }
      //3.需要一个弹窗
      //4.有确认和取消
      //5.确认  调用接口
      //6.成功 渲染数据
      //7.失败  提示
    },
    //自己定义格式化时间
    formatter(type, val) {
      if (type === "date") {
        const year = val.getFullYear();
        let month = val.getMonth() + 1;
        month = month > 9 ? month : "0" + month;
        let day = val.getDate();
        day = day > 9 ? day : "0" + day;
        const time = `${year}-${month}-${day}`;
        return time;
      } else {
        return val;
      }
    },
    //修改生日
    async editBirth(value) {
      const times = this.$formDate(value); //格式化时间 $formDate挂载到vue原型上了  main.js中
      try {
        await updateUserInfo({
          birthday: times //接口需要的格式 '2018-12-20'
        });
        // console.log(res);
        //将接口返回的数据赋值给  this.user.birthday
        this.user.birthday = times;
        this.showBirthday = false;
        this.$toast("修改成功");
      } catch {
        this.$toast("失败");
      }
    },
    //取消修改生日
    birthOnCancel() {
      this.showBirthday = false;
    },
    hPhotoChange() {
      this.editImage();
    },
    async editImage() {
      //获取图片信息  files文件对象  注意 绑定的input 必须是 type="file"
      const files = this.$refs.refPhoto.files[0];
      console.log(files);
      let fd = new FormData();
      //   console.log(fd);
      fd.append("photo", files);
      ///调用接口
      try {
        const res = await updatePhoto(fd);
        const resData = res.data.data;
        //项目安全性提升
        if (resData) {
          this.user.photo = resData.photo;
          this.$store.commit("savePhoto", resData.photo);
        }
      } catch {
        this.$toast("失败");
      }
      //成功渲染数据
      //失败提示
    }
  }
};
</script>

<style lang="less">
.van-nav-bar__text {
  color: #fff;
}
.user-image {
  position: relative;
}
.input-image {
  position: absolute;
  top: 10px;
  right: 0;
  z-index: 2;
  width: 100%;
  height: 100%;
  opacity: 0;
}
</style>
